package com._119yn.host.gst200.api.pointtable;

import com._119yn.host.gst200.database.entity.PointTableRecord;
import com._119yn.host.gst200.model.Rv;
import com._119yn.host.gst200.service.PointTableService;
import com._119yn.host.gst200.utils.PointTableRecordUtils;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("api/pointTable")
@RequiredArgsConstructor
public class PointTableController {

    private final PointTableService pointTableService;

    @SneakyThrows
    @PostMapping("import")
    public Rv importPointTable(MultipartFile file) {
        List<PointTableRecord> pointTableRecords;
        try (InputStream inputStream = file.getInputStream()) {
            Charset fileCharset = Charset.forName("GBK");
            pointTableRecords = PointTableRecordUtils.parse(inputStream, fileCharset);
        } catch (Exception e) {
            log.warn(e.getMessage());
            return Rv.error("解析失败");
        }
        try {
            pointTableService.importPointTable(pointTableRecords);
            return Rv.success("导入成功");
        } catch (Exception e) {
            log.warn(e.getMessage());
            return Rv.error("导入失败");
        }
    }

}
